<?php

namespace App\Model\Front;

use App\Model\Admin\Product;
use App\User;
use Gloudemans\Shoppingcart\Facades\Cart;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $fillable = ['total','status'];

    public function user()
    {
        return $this->belongsTo('App\User');
    }
  
    //关联中间表
    public function orderItems()
    {
        return $this->belongsToMany('App\Model\Admin\Product', 'order_products')->withPivot('qty', 'tax', 'total');
    }

    public function orders()
    {
        return $this->hasMany('App\Model\Front\OrderItem');
    }
 

    public static function SaveOrderToData($total)
    {
        $order = User::find(auth()->id())->orders()->create([

                    'total'=> $total,
                    'status'=>0

            ]);

        $cartItems = Cart::content();
        
        foreach ($cartItems as $cartItem) {
            $order->orderItems()->attach($cartItem->id, [
                'qty'=> $cartItem->qty,
                'tax'=>'0',
                'total'=> $cartItem->qty * $cartItem->price
                ]);
            $cartItem->stock -= $cartItem->qty;
            
            \DB::transaction(function () use ($cartItem) {
                // dd($cartItem->stock);
                Product::where('pro_code', $cartItem->id)->decrement('pro_stock', $cartItem->qty);
                ;
            });
            // echo ($cartItem->id);die;
        }
    }
}
